/**
 * 留言板
 */
 import React from 'react';
import './index.css'

class GuestBook extends React.Component{
    state={
        gname:'',
        gmsg:'',
        guestbookAllmsg:[]
    }
    formhadle=(e)=>{
        let t=e.target;//获取目标对象
        let val=t.type == 'checkbox'?t.checked:t.value//如果市复选框则是checked,其他的是value
        this.setState({
            [t.name]:val
        })
    }
    //发表留言
    addmsg=(e)=>{
        if(this.state.gname!=""&&this.state.gmsg!=""){
            let guest={
                'gname':this.state.gname,
                'gmsg':this.state.gmsg
            }
            this.setState({
                guestbookAllmsg:[guest,...this.state.guestbookAllmsg]
            })
            console.log(this.state.guestbookAllmsg);
            return;
        }
        alert("不能为空!")
    }
    isHave(){
        if(this.state.guestbookAllmsg.length==0){
            return <h2>暂无评论,快去评论吧~</h2>
        }
        let ok=this.state.guestbookAllmsg.map((msg)=>{
            return <li key={msg.gmsg}>评论者:{msg.gname}<br/>评论消息:{msg.gmsg}</li>; //jsx写法
        })
        return <ul>{ok}</ul>
    }
    render(){
        return(
            <div className='box'>
                <h1>留言板</h1>
                <input type="text" name='gname' onChange={this.formhadle} value={this.state.gname} placeholder="请输入评论人昵称" />
                <textarea onChange={this.formhadle} name='gmsg' value={this.state.gmsg} placeholder='评论消息'></textarea>
                <button onClick={this.addmsg}>发表</button>
                <div style={{'background':'pink'}}>{this.isHave()}</div>
            </div>
        )
    }
}
export default GuestBook